var Yselect = Vue.component('y-select', {
    data() {
        return {
            data: [],
            copydata: [],
            config: {},
            selectDataVis: false,
            selectValue: '',
            selectLabel: "",
            clearableState: false,
        };
    },
    props: {
        selectData: {
            type: Array,
            default: []
        },
        selectConfig: {
            type: Object,
            default: {
                // 显示字段
                labelName: 'label',
                // 绑定值
                valueName: 'value',
                // 树列表
                children: 'children',
                placeholder: '请选择',
                // key绑定字段
                key: 'value',
                // 默认显示字段
                label: '',
                // 默认显示值
                value: '',
                // 类型 tree img  default
                type: 'tree',
                // 是否可清空
                clearable: false,
                // 是否可搜索
                search: true,
                // 点击样式
                clickNumbel: null
            }
        },
    },
    provide() {
        return {
            getItemValue: this.getItemValue
        }
    },
    components: {
        "select-list": {
            name: 'select-list',
            props: {
                // 配置项
                data: {
                    type: Array,
                    default: []
                },
                config: {
                    type: Object,
                    default: {}
                },
                selectDataVis: {
                    type: Boolean,
                    default: false,
                }
            },
            data() {
                return {

                };
            },
            inject: ['getItemValue'],
            mounted() {

            },
            methods: {
                getValue: function(data, index, e) {
                    this.getItemValue(data, index, e)
                }
            },
            watch: {

            },
            template: `   <div class="tree-list">
            <ul>
                <li v-for="(item,index) in data" :key="item[config.key]"  @click.stop="getValue(item,index,$event)" >
                    <p :class="[config.clickNumbel===item[config.key]?'selected':'']">{{item[config.labelName]}}</p>
                    <select-list v-if="config.type=='tree'&&item[config.children]"  :data="item[config.children]"  :config="config" style=" padding-left:10px" />
                </li>
            </ul>
        </div>`
        }
    },
    created() {

    },
    watch: {
        selectData: {
            handler(n, o) {
                if (n) {
                    this.data = this.propsData;
                    this.copydata = JSON.parse(JSON.stringify(this.propsData));
                    this.init()
                }
            },
            deep: true,
            immediate: true,
        },
        selectLabel: {
            handler(n, o) {
                if (this.selectConfig.search) {
                    this.filterable(this.selectLabel)
                }
            }

        },

    },
    computed: {
        propsData() {
            return this.selectData
        }
    },
    mounted() {

    },
    methods: {
        init() {
            this.$nextTick(() => {
                this.config = this.selectConfig;
                var selectConfig = this.selectConfig;
                if (selectConfig.value) {
                    this.selectValue = selectConfig.value;
                    if (selectConfig.type == 'default') {
                        var [data] = this.selectData.filter(item => item[
                                selectConfig.valueName] ==
                            this
                            .selectValue);
                        this.selectLabel = data[selectConfig.labelName];
                    } else if (selectConfig.type == 'tree') {
                        var data = this.getChidlren({
                            type: selectConfig.valueName,
                            value: selectConfig.value,
                            children: selectConfig.children
                        })
                        this.selectLabel = data[selectConfig.labelName];
                        setTimeout(() => {
                            this.filterable('')
                        }, 50)
                    }

                }
            })
        },
        visShowData: function() {
            if (this.selectDataVis) {
                this.selectDataVis = false;
            } else {
                this.selectDataVis = true;
                this.data = this.propsData;
            }
        },
        getItemValue: function(data, index, e) {
            this.selectValue = data[this.selectConfig.valueName];
            this.selectLabel = data[this.selectConfig.labelName];
            this.selectDataVis = false;
            this.selectConfig.clickNumbel = data[this.selectConfig.key];
        },
        enter: function() {
            // 进
            if (!this.selectConfig.clearable) return false;
            if (this.selectValue) {
                this.clearableState = true;

            }
            // this.$refs.iconDown

        },
        leave: function() {
            // 出
            if (!this.selectConfig.clearable) return false;
            if (this.selectValue) {
                this.clearableState = false;

            }
        },
        clearable: function() {
            if (!this.selectConfig.clearable) return false;
            this.selectValue = '';
            this.selectLabel = '';
            this.clearableState = false;
            this.selectDataVis = false;
        },
        getChidlren(Setting) {
            // type 查找值Key value查找的值  children 树形字数组key
            var defaultSetting = {
                type: 'id',
                value: 'id',
                children: 'children'
            }
            var newSetting = Object.assign({}, defaultSetting, Setting);
            var hasFound = false, // 表示是否有找到id值
                result = null;
            var fn = function(data) {
                if (Array.isArray(data) && !hasFound) { // 判断是否是数组并且没有的情况下，
                    data.forEach(item => {
                        if (item[newSetting.type] === newSetting
                            .value) { // 数据循环每个子项，并且判断子项下边是否有id值
                            result = item; // 返回的结果等于每一项
                            hasFound = true; // 并且找到id值
                        } else if (item[newSetting.children]) {
                            fn(item[[newSetting.children]]); // 递归调用下边的子项
                        }
                    })
                }
            }
            fn(this.copydata); // 调用一下
            return result;
        },
        filterable(value) {
            this.data = this.filterData(this.copydata, node => node[this.selectConfig.labelName].indexOf(
                value) != -1);
        },
        /**
         * 递归过滤节点，生成新的树结构
         * @param {Node[]} nodes 要过滤的节点
         * @param {node => boolean} predicate 过滤条件，符合条件的节点保留
         * @return 过滤后的节点
         */
        filterData(nodes, predicate) {
            // 如果已经没有节点了，结束递归
            if (!(nodes && nodes.length)) {
                return [];
            }

            const newChildren = [];
            for (const node of nodes) {
                if (predicate(node)) {
                    // 如果节点符合条件，直接加入新的节点集
                    newChildren.push(node);
                    node[this.selectConfig.children] = this.filterData(node[this.selectConfig.children],
                        predicate);
                } else {
                    // 如果当前节点不符合条件，递归过滤子节点，
                    // 把符合条件的子节点提升上来，并入新节点集
                    newChildren.push(...this.filterData(node[this.selectConfig.children], predicate));
                }
            }
            return newChildren;
        }
    },
    template: `
    <div class="yselect">
    <div class="tree-input" @click="visShowData" @mouseenter="enter()" @mouseleave="leave()">
        <input v-model="selectLabel" :placeholder="selectConfig.placeholder" :readonly='!selectConfig.search' />
        <span :class="[clearableState ? 'cancelactive' : '', 'iconfont', 'icon-cancel']" @click.stop="clearable" v-show="clearableState"></span>
        <span class="iconfont icon-down" v-show="clearableState?false:!selectDataVis" ref="iconDown"></span>
        <span class="iconfont icon-upward" v-show="clearableState?false:selectDataVis"></span>
    </div>
    <div class="tree-box" v-show="selectDataVis">
        <select-list :data="data" :config="selectConfig" />
    </div>
</div>
    `
});